package com.lifeverse.service;

import com.lifeverse.entity.BehaviorPattern;
import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.enums.PatternStatus;
import com.lifeverse.entity.enums.PatternType;
import com.lifeverse.repository.BehaviorPatternRepository;
import com.lifeverse.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生命体行为模式分析器
 * 负责分析生命体的行为模式，识别规律和异常
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class BehaviorPatternAnalyzer {

    private final BehaviorPatternRepository behaviorPatternRepository;
    private final JsonUtils jsonUtils;

    /**
     * 分析生命体的行为模式
     */
    @Transactional
    public List<BehaviorPattern> analyzeLifeEntityBehavior(LifeEntity lifeEntity, Map<String, Object> behaviorData) {
        log.info("开始分析生命体 {} 的行为模式", lifeEntity.getId());
        
        List<BehaviorPattern> detectedPatterns = new ArrayList<>();
        
        try {
            // 1. 分析决策模式
            BehaviorPattern decisionPattern = analyzeDecisionPattern(lifeEntity, behaviorData);
            if (decisionPattern != null) {
                detectedPatterns.add(decisionPattern);
            }
            
            // 2. 分析交互模式
            BehaviorPattern interactionPattern = analyzeInteractionPattern(lifeEntity, behaviorData);
            if (interactionPattern != null) {
                detectedPatterns.add(interactionPattern);
            }
            
            // 3. 分析学习模式
            BehaviorPattern learningPattern = analyzeLearningPattern(lifeEntity, behaviorData);
            if (learningPattern != null) {
                detectedPatterns.add(learningPattern);
            }
            
            // 4. 分析资源使用模式
            BehaviorPattern resourcePattern = analyzeResourceUsagePattern(lifeEntity, behaviorData);
            if (resourcePattern != null) {
                detectedPatterns.add(resourcePattern);
            }
            
            // 5. 保存检测到的模式
            detectedPatterns = behaviorPatternRepository.saveAll(detectedPatterns);
            
            log.info("为生命体 {} 检测到 {} 个行为模式", lifeEntity.getId(), detectedPatterns.size());
            
        } catch (Exception e) {
            log.error("分析生命体 {} 行为模式时发生错误", lifeEntity.getId(), e);
        }
        
        return detectedPatterns;
    }

    /**
     * 分析决策模式
     */
    private BehaviorPattern analyzeDecisionPattern(LifeEntity lifeEntity, Map<String, Object> behaviorData) {
        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> decisions = (List<Map<String, Object>>) behaviorData.get("decisions");
            
            if (decisions == null || decisions.isEmpty()) {
                return null;
            }
            
            // 计算决策特征
            Map<String, Double> features = new HashMap<>();
            features.put("decision_count", (double) decisions.size());
            features.put("avg_decision_time", calculateAverageDecisionTime(decisions));
            features.put("success_rate", calculateDecisionSuccessRate(decisions));
            features.put("complexity_preference", calculateComplexityPreference(decisions));
            
            // 计算置信度
            double confidence = calculatePatternConfidence(features, PatternType.DECISION);
            
            if (confidence >= 0.6) {
                BehaviorPattern pattern = new BehaviorPattern();
                pattern.setLifeEntityId(lifeEntity.getId());
                pattern.setPatternType(PatternType.DECISION);
                pattern.setPatternName("决策行为模式");
                pattern.setDescription("生命体的决策行为特征分析");
                pattern.setFeatureVector(jsonUtils.toJson(features));
                pattern.setConfidenceScore(confidence);
                pattern.setFrequency(decisions.size());
                pattern.setStatus(PatternStatus.ACTIVE);
                pattern.setFirstDetectedAt(LocalDateTime.now());
                pattern.setLastDetectedAt(LocalDateTime.now());
                pattern.setAnomalyScore(calculateAnomalyScore(features));
                
                return pattern;
            }
            
        } catch (Exception e) {
            log.error("分析决策模式时发生错误", e);
        }
        
        return null;
    }

    /**
     * 分析交互模式
     */
    private BehaviorPattern analyzeInteractionPattern(LifeEntity lifeEntity, Map<String, Object> behaviorData) {
        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> interactions = (List<Map<String, Object>>) behaviorData.get("interactions");
            
            if (interactions == null || interactions.isEmpty()) {
                return null;
            }
            
            // 计算交互特征
            Map<String, Double> features = new HashMap<>();
            features.put("interaction_count", (double) interactions.size());
            features.put("avg_interaction_duration", calculateAverageInteractionDuration(interactions));
            features.put("interaction_diversity", calculateInteractionDiversity(interactions));
            features.put("collaboration_ratio", calculateCollaborationRatio(interactions));
            
            double confidence = calculatePatternConfidence(features, PatternType.INTERACTION);
            
            if (confidence >= 0.6) {
                BehaviorPattern pattern = new BehaviorPattern();
                pattern.setLifeEntityId(lifeEntity.getId());
                pattern.setPatternType(PatternType.INTERACTION);
                pattern.setPatternName("交互行为模式");
                pattern.setDescription("生命体的交互行为特征分析");
                pattern.setFeatureVector(jsonUtils.toJson(features));
                pattern.setConfidenceScore(confidence);
                pattern.setFrequency(interactions.size());
                pattern.setStatus(PatternStatus.ACTIVE);
                pattern.setFirstDetectedAt(LocalDateTime.now());
                pattern.setLastDetectedAt(LocalDateTime.now());
                pattern.setAnomalyScore(calculateAnomalyScore(features));
                
                return pattern;
            }
            
        } catch (Exception e) {
            log.error("分析交互模式时发生错误", e);
        }
        
        return null;
    }

    /**
     * 分析学习模式
     */
    private BehaviorPattern analyzeLearningPattern(LifeEntity lifeEntity, Map<String, Object> behaviorData) {
        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> learningEvents = (List<Map<String, Object>>) behaviorData.get("learning_events");
            
            if (learningEvents == null || learningEvents.isEmpty()) {
                return null;
            }
            
            // 计算学习特征
            Map<String, Double> features = new HashMap<>();
            features.put("learning_frequency", (double) learningEvents.size());
            features.put("learning_efficiency", calculateLearningEfficiency(learningEvents));
            features.put("knowledge_retention", calculateKnowledgeRetention(learningEvents));
            features.put("adaptation_speed", calculateAdaptationSpeed(learningEvents));
            
            double confidence = calculatePatternConfidence(features, PatternType.LEARNING);
            
            if (confidence >= 0.6) {
                BehaviorPattern pattern = new BehaviorPattern();
                pattern.setLifeEntityId(lifeEntity.getId());
                pattern.setPatternType(PatternType.LEARNING);
                pattern.setPatternName("学习行为模式");
                pattern.setDescription("生命体的学习行为特征分析");
                pattern.setFeatureVector(jsonUtils.toJson(features));
                pattern.setConfidenceScore(confidence);
                pattern.setFrequency(learningEvents.size());
                pattern.setStatus(PatternStatus.ACTIVE);
                pattern.setFirstDetectedAt(LocalDateTime.now());
                pattern.setLastDetectedAt(LocalDateTime.now());
                pattern.setAnomalyScore(calculateAnomalyScore(features));
                
                return pattern;
            }
            
        } catch (Exception e) {
            log.error("分析学习模式时发生错误", e);
        }
        
        return null;
    }

    /**
     * 分析资源使用模式
     */
    private BehaviorPattern analyzeResourceUsagePattern(LifeEntity lifeEntity, Map<String, Object> behaviorData) {
        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> resourceUsage = (List<Map<String, Object>>) behaviorData.get("resource_usage");
            
            if (resourceUsage == null || resourceUsage.isEmpty()) {
                return null;
            }
            
            // 计算资源使用特征
            Map<String, Double> features = new HashMap<>();
            features.put("resource_efficiency", calculateResourceEfficiency(resourceUsage));
            features.put("usage_consistency", calculateUsageConsistency(resourceUsage));
            features.put("peak_usage_ratio", calculatePeakUsageRatio(resourceUsage));
            features.put("waste_ratio", calculateWasteRatio(resourceUsage));
            
            double confidence = calculatePatternConfidence(features, PatternType.RESOURCE_USAGE);
            
            if (confidence >= 0.6) {
                BehaviorPattern pattern = new BehaviorPattern();
                pattern.setLifeEntityId(lifeEntity.getId());
                pattern.setPatternType(PatternType.RESOURCE_USAGE);
                pattern.setPatternName("资源使用模式");
                pattern.setDescription("生命体的资源使用特征分析");
                pattern.setFeatureVector(jsonUtils.toJson(features));
                pattern.setConfidenceScore(confidence);
                pattern.setFrequency(resourceUsage.size());
                pattern.setStatus(PatternStatus.ACTIVE);
                pattern.setFirstDetectedAt(LocalDateTime.now());
                pattern.setLastDetectedAt(LocalDateTime.now());
                pattern.setAnomalyScore(calculateAnomalyScore(features));
                
                return pattern;
            }
            
        } catch (Exception e) {
            log.error("分析资源使用模式时发生错误", e);
        }
        
        return null;
    }

    /**
     * 计算平均决策时间
     */
    private double calculateAverageDecisionTime(List<Map<String, Object>> decisions) {
        return decisions.stream()
                .mapToDouble(d -> ((Number) d.getOrDefault("decision_time", 0)).doubleValue())
                .average()
                .orElse(0.0);
    }

    /**
     * 计算决策成功率
     */
    private double calculateDecisionSuccessRate(List<Map<String, Object>> decisions) {
        long successCount = decisions.stream()
                .mapToLong(d -> ((Boolean) d.getOrDefault("success", false)) ? 1 : 0)
                .sum();
        return decisions.isEmpty() ? 0.0 : (double) successCount / decisions.size();
    }

    /**
     * 计算复杂度偏好
     */
    private double calculateComplexityPreference(List<Map<String, Object>> decisions) {
        return decisions.stream()
                .mapToDouble(d -> ((Number) d.getOrDefault("complexity", 0)).doubleValue())
                .average()
                .orElse(0.0);
    }

    /**
     * 计算平均交互持续时间
     */
    private double calculateAverageInteractionDuration(List<Map<String, Object>> interactions) {
        return interactions.stream()
                .mapToDouble(i -> ((Number) i.getOrDefault("duration", 0)).doubleValue())
                .average()
                .orElse(0.0);
    }

    /**
     * 计算交互多样性
     */
    private double calculateInteractionDiversity(List<Map<String, Object>> interactions) {
        Set<String> uniqueTypes = interactions.stream()
                .map(i -> (String) i.getOrDefault("type", "unknown"))
                .collect(Collectors.toSet());
        return interactions.isEmpty() ? 0.0 : (double) uniqueTypes.size() / interactions.size();
    }

    /**
     * 计算协作比率
     */
    private double calculateCollaborationRatio(List<Map<String, Object>> interactions) {
        long collaborationCount = interactions.stream()
                .mapToLong(i -> "collaboration".equals(i.get("type")) ? 1 : 0)
                .sum();
        return interactions.isEmpty() ? 0.0 : (double) collaborationCount / interactions.size();
    }

    /**
     * 计算学习效率
     */
    private double calculateLearningEfficiency(List<Map<String, Object>> learningEvents) {
        return learningEvents.stream()
                .mapToDouble(e -> ((Number) e.getOrDefault("efficiency", 0)).doubleValue())
                .average()
                .orElse(0.0);
    }

    /**
     * 计算知识保持率
     */
    private double calculateKnowledgeRetention(List<Map<String, Object>> learningEvents) {
        return learningEvents.stream()
                .mapToDouble(e -> ((Number) e.getOrDefault("retention", 0)).doubleValue())
                .average()
                .orElse(0.0);
    }

    /**
     * 计算适应速度
     */
    private double calculateAdaptationSpeed(List<Map<String, Object>> learningEvents) {
        return learningEvents.stream()
                .mapToDouble(e -> ((Number) e.getOrDefault("adaptation_speed", 0)).doubleValue())
                .average()
                .orElse(0.0);
    }

    /**
     * 计算资源效率
     */
    private double calculateResourceEfficiency(List<Map<String, Object>> resourceUsage) {
        return resourceUsage.stream()
                .mapToDouble(r -> ((Number) r.getOrDefault("efficiency", 0)).doubleValue())
                .average()
                .orElse(0.0);
    }

    /**
     * 计算使用一致性
     */
    private double calculateUsageConsistency(List<Map<String, Object>> resourceUsage) {
        double[] values = resourceUsage.stream()
                .mapToDouble(r -> ((Number) r.getOrDefault("usage_amount", 0)).doubleValue())
                .toArray();
        
        if (values.length < 2) return 1.0;
        
        DescriptiveStatistics stats = new DescriptiveStatistics(values);
        double mean = stats.getMean();
        double stdDev = stats.getStandardDeviation();
        
        return mean == 0 ? 1.0 : 1.0 - (stdDev / mean);
    }

    /**
     * 计算峰值使用比率
     */
    private double calculatePeakUsageRatio(List<Map<String, Object>> resourceUsage) {
        double maxUsage = resourceUsage.stream()
                .mapToDouble(r -> ((Number) r.getOrDefault("usage_amount", 0)).doubleValue())
                .max()
                .orElse(0.0);
        
        double avgUsage = resourceUsage.stream()
                .mapToDouble(r -> ((Number) r.getOrDefault("usage_amount", 0)).doubleValue())
                .average()
                .orElse(0.0);
        
        return avgUsage == 0 ? 0.0 : maxUsage / avgUsage;
    }

    /**
     * 计算浪费比率
     */
    private double calculateWasteRatio(List<Map<String, Object>> resourceUsage) {
        return resourceUsage.stream()
                .mapToDouble(r -> ((Number) r.getOrDefault("waste_ratio", 0)).doubleValue())
                .average()
                .orElse(0.0);
    }

    /**
     * 计算模式置信度
     */
    private double calculatePatternConfidence(Map<String, Double> features, PatternType patternType) {
        // 基于特征值计算置信度的简化算法
        double sum = features.values().stream().mapToDouble(Double::doubleValue).sum();
        double count = features.size();
        
        if (count == 0) return 0.0;
        
        double baseConfidence = Math.min(sum / count, 1.0);
        
        // 根据模式类型调整置信度
        switch (patternType) {
            case DECISION:
                return Math.min(baseConfidence * 1.1, 1.0);
            case INTERACTION:
                return Math.min(baseConfidence * 1.05, 1.0);
            case LEARNING:
                return Math.min(baseConfidence * 1.15, 1.0);
            case RESOURCE_USAGE:
                return Math.min(baseConfidence * 1.0, 1.0);
            default:
                return baseConfidence;
        }
    }

    /**
     * 计算异常分数
     */
    private double calculateAnomalyScore(Map<String, Double> features) {
        // 简化的异常检测算法
        double[] values = features.values().stream().mapToDouble(Double::doubleValue).toArray();
        
        if (values.length < 2) return 0.0;
        
        DescriptiveStatistics stats = new DescriptiveStatistics(values);
        double mean = stats.getMean();
        double stdDev = stats.getStandardDeviation();
        
        // 计算Z-score的平均值作为异常分数
        double totalZScore = 0.0;
        for (double value : values) {
            if (stdDev > 0) {
                totalZScore += Math.abs((value - mean) / stdDev);
            }
        }
        
        double avgZScore = totalZScore / values.length;
        return Math.min(avgZScore / 3.0, 1.0); // 标准化到0-1范围
    }

    /**
     * 更新现有模式
     */
    @Transactional
    public void updateExistingPatterns(Long lifeEntityId) {
        List<BehaviorPattern> existingPatterns = behaviorPatternRepository.findByLifeEntityId(lifeEntityId);
        
        for (BehaviorPattern pattern : existingPatterns) {
            // 检查模式是否过期
            if (isPatternExpired(pattern)) {
                pattern.setStatus(PatternStatus.EXPIRED);
                behaviorPatternRepository.save(pattern);
            }
        }
    }

    /**
     * 检查模式是否过期
     */
    private boolean isPatternExpired(BehaviorPattern pattern) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime lastDetected = pattern.getLastDetectedAt();
        
        // 如果超过7天没有检测到该模式，则认为过期
        return ChronoUnit.DAYS.between(lastDetected, now) > 7;
    }
}